<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Controller</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.4.0pr3/build/cssgrids/grids-min.css">
    <link rel="stylesheet" href="../assets/css/main.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <script src="../../build/yui/yui-min.js"></script>
</head>
<body>

<div id="doc">
    <h1>Controller</h1>

    
        <a href="#toc" class="jump">Jump to Table of Contents</a>
    

    <div class="yui3-g">
        <div id="main" class="yui3-u">
            <div class="content"><div class="intro">
<p>
Controller provides URL-based same-page routing using <a href="https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history">HTML5 history</a> (<code>pushState</code>) or the location hash, depending on what the user's browser supports.
</p>

<p>
This makes it easy to wire up route handlers for different application states while providing full back/forward navigation support and bookmarkable, shareable URLs, all handled entirely on the client.
</p>

<p>
If you've used a server-side routing framework like <a href="http://expressjs.com/">Express</a> or <a href="http://www.sinatrarb.com/">Sinatra</a>, Controller will look very familiar to you. This is no accident!
</p>
</div>

<h2 id="getting-started">Getting Started</h2>

<p>
To include the source files for Controller and its dependencies, first load
the YUI seed file if you haven't already loaded it.
</p>

<pre class="code prettyprint">&lt;script src=&quot;http:&#x2F;&#x2F;yui.yahooapis.com&#x2F;3.4.1&#x2F;build&#x2F;yui&#x2F;yui-min.js&quot;&gt;&lt;&#x2F;script&gt;</pre>


<p>
Next, create a new YUI instance for your application and populate it with the
modules you need by specifying them as arguments to the <code>YUI().use()</code> method.
YUI will automatically load any dependencies required by the modules you
specify.
</p>

<pre class="code prettyprint">&#x2F;&#x2F; Create a new YUI instance and populate it with the required modules.
YUI().use(&#x27;controller&#x27;, function (Y) {
    &#x2F;&#x2F; Controller is available and ready for use. Add implementation
    &#x2F;&#x2F; code here.
});</pre>


<p>
For more information on creating YUI instances and on the
<a href="http://yuilibrary.com/yui/docs/api/classes/YUI.html#method_use"><code>use()</code> method</a>, see the
documentation for the <a href="../yui/index.html">YUI Global object</a>.
</p>


<h2 id="url-based-routing-on-the-client">URL-based Routing on the Client?</h2>

<p>
You bet! URLs are an excellent way to maintain state in a web app, since they're easy to read, easy to change, and can be bookmarked and shared.
</p>

<p>
Server-side web frameworks use URLs to maintain state by routing them to different pages and by storing information in query strings. These same techniques can now be used by client-side web apps to achieve better parity with server-side logic and to provide a more seamless user experience.
</p>

<p>
Controller allows you to define routes that map to callback functions. Whenever the user navigates to a URL that matches a route you've defined, that route's callback function is executed and can update the UI, make Ajax requests, or perform any other necessary actions. See <a href="#routing">Routing</a> for more details on how this works.
</p>

<p>
Often you'll want to change the URL in order to trigger a route handler, perhaps because the user has taken an action that should change the state of your application. Controller provides a <code>save()</code> method that sets a new URL and saves it to the user's browser history. There's also a <code>replace()</code> method to replace the current URL in the user's browser history without creating a new entry. The <a href="#updating-the-url">Updating the URL</a> section describes these methods in detail.
</p>

<h2 id="sample-urls">Sample URLs</h2>

<p>
In browsers that support the HTML5 history API, Controller generates real URLs that can gracefully degrade to allow server-side handling of initial pageviews or pageviews without JS enabled. Most modern browsers (including recent versions of Firefox, Chrome, Safari, and Mobile Safari) support HTML5 history.
</p>

<p>
In browsers that don't support the HTML5 history API, Controller falls back on using the location hash to store URL information and trigger history changes. This mostly applies only to older browsers and Internet Explorer. Unfortunately, even Internet Explorer 9 doesn't support the HTML5 history API.
</p>

<p>
The table below contains examples of the kinds of URLs Controller might generate when the <code>save()</code> method is called on a Controller instance, starting from an initial URL of <code>http:&#x2F;&#x2F;example.com&#x2F;</code>.
</p>

<table>
  <thead>
    <tr>
      <th>Code</th>
      <th>HTML5 URL</th>
      <th>Legacy URL</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code>controller.save(&#x27;&#x2F;&#x27;)</code></td>
      <td><code>http:&#x2F;&#x2F;example.com&#x2F;</code></td>
      <td><code>http:&#x2F;&#x2F;example.com&#x2F;#&#x2F;</code></td>
    </tr>

    <tr>
      <td><code>controller.save(&#x27;&#x2F;pie&#x2F;yum&#x27;)</code></td>
      <td><code>http:&#x2F;&#x2F;example.com&#x2F;pie&#x2F;yum</code></td>
      <td><code>http:&#x2F;&#x2F;example.com&#x2F;#&#x2F;pie&#x2F;yum</code></td>
    </tr>

    <tr>
      <td><code>controller.save(&#x27;&#x2F;pie?type=pecan&amp;icecream=true&#x27;)</code></td>
      <td><code>http:&#x2F;&#x2F;example.com&#x2F;pie?type=pecan&amp;icecream=true</code></td>
      <td><code>http:&#x2F;&#x2F;example.com&#x2F;#&#x2F;pie?type=pecan&amp;icecream=true</code></td>
    </tr>
  </tbody>
</table>

<h2 id="using-controller">Using Controller</h2>

<h3 id="instantiating-controller">Instantiating Controller</h3>

<p>
To begin adding route handlers, the first thing you'll need to do is create a new Controller instance.
</p>

<pre class="code prettyprint">var controller = new Y.Controller();</pre>


<p>
This is the simplest way of working with Controller, but you may also extend <code>Y.Controller</code> to create a custom Controller class that suits your needs. The <a href="#extending-ycontroller">Extending <code>Y.Controller</code></a> section explains how to do this.
</p>

<h4 id="config-properties">Config Properties</h4>

<p>
When instantiating Controller, you may optionally pass in a config object containing any of the following properties. For more details on these properties, see Controller's <a href="http://yuilibrary.com/yui/docs/api/modules/module_controller.html">API docs</a>.
</p>

<table>
  <thead>
    <tr>
      <th>Property</th>
      <th>Default</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code>root</code></td>
      <td><code>&#x27;&#x27;</code></td>
      <td>
        <p>
        Root path from which all routes should be evaluated. See <a href="#setting-the-root-path">Setting the Root Path</a> for details.
        </p>
      </td>
    </tr>

    <tr>
      <td><code>routes</code></td>
      <td><code>[]</code></td>
      <td>
        <p>
        Array of route objects specifying routes to be created at instantiation time. This can be used as an alternative to adding routes via the <code>route()</code> method after instantiation.
        </p>

        <p>
        Each item in the array must be an object with the following properties:
        </p>

        <dl style="margin-top:1em">
          <dt><code>path</code></dt>
          <dd>
            String or regex representing the path to match. See <a href="#routing">Routing</a> for more details.
          </dd>

          <dt><code>callback</code></dt>
          <dd>
            A function or a string representing the name of a function on the Controller instance that should be called when the route is triggered. See <a href="#routing">Routing</a> for more details.
          </dd>
        </dl>
      </td>
    </tr>
  </tbody>
</table>

<p>
Here's an example that sets all the configurable properties:
</p>

<pre class="code prettyprint">var controller = new Y.Controller({
  root: &#x27;&#x2F;mysite&#x27;,

  routes: [
    {path: &#x27;&#x2F;&#x27;,    callback: function () { alert(&#x27;Hello!&#x27;); }},
    {path: &#x27;&#x2F;pie&#x27;, callback: function () { alert(&#x27;Mmm. Pie.&#x27;); }}
  ]
});</pre>


<h4 id="read-only-properties">Read-Only Properties</h4>

<p>
Controller instances currently expose a single informational property, <code>html5</code>, which is meant to be read-only.
</p>

<table>
  <thead>
    <tr>
      <th>Property</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code>html5</code></td>
      <td>
        <p>
        Whether or not the user's browser is capable of using HTML5 history.
        </p>

        <p>
        This property is for informational purposes only. It's not configurable, and changing it will have no effect.
        </p>
      </td>
    </tr>
  </tbody>
</table>

<h4 id="setting-the-root-path">Setting the Root Path</h4>

<p>
Let's say the URL for your website is <code>http:&#x2F;&#x2F;example.com&#x2F;mysite&#x2F;</code>. Since Controller matches routes based on the URL path, it would look for routes beginning with <code>&#x2F;mysite&#x2F;</code>.
</p>

<p>
You could deal with this by ensuring that all your routes start with <code>&#x2F;mysite&#x2F;</code>, but that's tedious, and it won't work well if you're writing a component that might be used on various sites where you can't anticipate the root path.
</p>

<p>
This is where the <code>root</code> config property comes in. If you set <code>root</code> to <code>&#x27;&#x2F;mysite&#x27;</code>, then all routes will be evaluated relative to that root path, as illustrated below.
</p>

<p>
The <code>root</code> must be an absolute path.
</p>

<table>
  <thead>
    <tr>
      <th>URL</th>
      <th>Route (No root)</th>
      <th>Route (Root: /mysite)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code>http:&#x2F;&#x2F;example.com&#x2F;mysite&#x2F;</code></td>
      <td><code>&#x2F;mysite&#x2F;</code></td>
      <td><code>&#x2F;</code></td>
    </tr>

    <tr>
      <td><code>http:&#x2F;&#x2F;example.com&#x2F;mysite&#x2F;pie&#x2F;</code></td>
      <td><code>&#x2F;mysite&#x2F;pie&#x2F;</code></td>
      <td><code>&#x2F;pie&#x2F;</code></td>
    </tr>

    <tr>
      <td><code>http:&#x2F;&#x2F;example.com&#x2F;mysite&#x2F;ice-cream&#x2F;yum.html</code></td>
      <td><code>&#x2F;mysite&#x2F;ice-cream&#x2F;yum.html</code></td>
      <td><code>&#x2F;ice-cream&#x2F;yum.html</code></td>
    </tr>
  </tbody>
</table>

<h3 id="extending-ycontroller">Extending <code>Y.Controller</code></h3>

<p>
While <code>Y.Controller</code> may be instantiated and used directly, you might find it more convenient to extend the <code>Y.Controller</code> class to create a subclass customized for your particular needs.
</p>

<p>
Use the <code>Y.Base.create()</code> method to extend <code>Y.Controller</code> and add or override prototype and static members. You may also optionally specify one or more <a href="../base/index.html#extensions">Base extensions</a> to mix into your new class.
</p>

<pre class="code prettyprint">&#x2F;&#x2F; Create a Y.CustomController class that extends Y.Controller.
Y.CustomController = Y.Base.create(&#x27;customController&#x27;, Y.Controller, [], {
  &#x2F;&#x2F; Add or override prototype properties and methods here.
}, {
  &#x2F;&#x2F; Add static properties and methods here.
});</pre>


<p>
One benefit of extending <code>Y.Controller</code> is that you can easily add default config properties, routes, and route handlers to the prototype of your custom Controller class, and they'll be shared by all instances of that class unless overridden at the instance level:
</p>

<pre class="code prettyprint">Y.CustomController = Y.Base.create(&#x27;customController&#x27;, Y.Controller, [], {
  &#x2F;&#x2F; Evaluate all routes relative to this root path.
  root: &#x27;&#x2F;mysite&#x27;,

  &#x2F;&#x2F; Share these default routes with all CustomController instances.
  routes: [
    {path: &#x27;&#x2F;&#x27;,    callback: &#x27;index&#x27;},
    {path: &#x27;&#x2F;pie&#x27;, callback: &#x27;pie&#x27;}
  ],

  &#x2F;&#x2F; Default route handlers inherited by all CustomController instances.
  index: function (req) {
    &#x2F;&#x2F; ... handle the &#x2F; route ...
  },

  pie: function (req) {
    &#x2F;&#x2F; ... handle the &#x2F;pie route ...
  }
});

&#x2F;&#x2F; Create a CustomController instance that inherits the defaults and adds to
&#x2F;&#x2F; them.
var controller = new Y.CustomController();

controller.route(&#x27;&#x2F;cheesecake&#x27;, function (req) {
  &#x2F;&#x2F; ... handle the &#x2F;cheesecake route
});</pre>


<p>
Now all instances of <code>Y.CustomController</code> will inherit all the custom defaults and can add to or override them. The <code>controller</code> instance created here will handle the <code>&#x2F;</code> and <code>&#x2F;pie</code> routes in addition to its own <code>&#x2F;cheesecake</code> route, and will evaluate all routes from the <code>&#x2F;mysite</code> root path.
</p>

<h3 id="routing">Routing</h3>

<p>
Use the <code>route()</code> method to add a new route to a Controller instance. The first parameter is a path specification or regular expression that the URL path must match, and the second parameter is a callback function or function name to execute when the route is matched.
</p>

<pre class="code prettyprint">var controller = new Y.Controller();

&#x2F;&#x2F; Add a route using a string as the path specification.
controller.route(&#x27;&#x2F;pie&#x27;, function () {
  Y.log(&#x27;You visited http:&#x2F;&#x2F;example.com&#x2F;pie&#x27;);
});

&#x2F;&#x2F; Add a route using a regular expression as the path specification.
controller.route(&#x2F;^\&#x2F;cake$&#x2F;, function () {
  Y.log(&#x27;You visited http:&#x2F;&#x2F;example.com&#x2F;cake&#x27;);
});</pre>


<p>
Routes are always evaluated in the order they're added. The first route that matches a given URL is executed, and any subsequent routes that also match the URL will not be executed unless the first route passes control to the next route. See <a href="#chaining-routes">Chaining Routes</a> for more info on executing more than one route for a given URL.
</p>

<p>
When a route callback is specified as a string instead of a function, it's assumed to represent the name of a function on the Controller instance.
</p>

<pre class="code prettyprint">var controller = new Y.Controller();

controller.pie = function () {
  Y.log(&#x27;You visited http:&#x2F;&#x2F;example.com&#x2F;pie&#x27;);
};

&#x2F;&#x2F; Add a route using controller.pie as the route callback.
controller.route(&#x27;&#x2F;pie&#x27;, &#x27;pie&#x27;);</pre>


<p>
As an alternative to using the <code>route()</code> method, routes may be added at instantiation time using the <code>routes</code> config property:
</p>

<pre class="code prettyprint">var controller = new Y.Controller({
  routes: [
    {path: &#x27;&#x2F;pie&#x27;, callback: function () {
      Y.log(&#x27;You visited http:&#x2F;&#x2F;example.com&#x2F;pie&#x27;);
    }},

    {path: &#x2F;^\&#x2F;cake$&#x2F;, callback: function () {
      Y.log(&#x27;You visited http:&#x2F;&#x2F;example.com&#x2F;cake&#x27;);
    }}
  ]
});</pre>


<p>
This is functionally equivalent to adding the routes via the <code>route()</code> method, except that the routes are added during the Controller's initialization stage rather than after.
</p>

<h4 id="paths-placeholders-and-regexps">Paths, Placeholders, and RegExps</h4>

<p>
A route path may be specified as either a string or a regular expression. When a string is provided, it's compiled to a regular expression internally. If the regex matches the path portion (not including protocol, domain, query string, etc.) of a URL being dispatched, the route callback will be executed.
</p>

<p>
Path strings may contain placeholders. When a route is matched, the values of these placeholders will be made available to the route callback on the <code>req.params</code> object.
</p>

<p>
A placeholder prefixed by a <code>:</code>, like <code>:pie</code>, will match any character except for a path separator (<code>&#x2F;</code>).
</p>

<pre class="code prettyprint">controller.route(&#x27;&#x2F;pie&#x2F;:type&#x2F;:slices&#x27;, function (req) {
  Y.log(&quot;You ordered &quot; + req.params.slices + &quot; slices of &quot;
      + req.params.type + &quot; pie.&quot;);
});

controller.save(&#x27;&#x2F;pie&#x2F;apple&#x2F;2&#x27;);
&#x2F;&#x2F; =&gt; &quot;You ordered 2 slices of apple pie.&quot;

controller.save(&#x27;&#x2F;pie&#x2F;lemon+meringue&#x2F;42&#x27;);
&#x2F;&#x2F; =&gt; &quot;You ordered 42 slices of lemon meringue pie.&quot;</pre>


<p>
A placeholder prefixed by a <code>*</code>, like <code>*path</code>, will match as many characters as it can until the next character after the placeholder, including path separators.
</p>

<pre class="code prettyprint">controller.route(&#x27;&#x2F;files&#x2F;*path&#x27;, function (req) {
  Y.log(&quot;You requested the file &quot; + req.params.path);
});

controller.save(&#x27;&#x2F;files&#x2F;recipes&#x2F;pie&#x2F;pecan.html&#x27;);
&#x2F;&#x2F; =&gt; &quot;You requested the file recipes&#x2F;pie&#x2F;pecan.html&quot;</pre>


<p>
Placeholder names may contain any character in the range <code>[A-Za-z0-9_-]</code> (so <code>:foo-bar</code> is a valid placeholder but <code>:foo bar</code> is not).
</p>

<p>
When a regular expression is used as a path specification, <code>req.params</code> will be an array. The first item in the array is the entire matched string, and subsequent items are captured subpattern matches (if any).
</p>

<pre class="code prettyprint">controller.route(&#x2F;^\&#x2F;pie\&#x2F;([^\&#x2F;]*)\&#x2F;([^\&#x2F;]*)$&#x2F;, function (req) {
  Y.log(&quot;You ordered &quot; + req.params[1] + &quot; slices of &quot;
      + req.params[2] + &quot; pie.&quot;);
});

controller.save(&#x27;&#x2F;pie&#x2F;maple+custard&#x2F;infinity&#x27;);
&#x2F;&#x2F; =&gt; &quot;You ordered infinity slices of maple custard pie.&quot;</pre>


<h4 id="route-callbacks">Route Callbacks</h4>

<p>
When a route is matched, the callback function associated with that route will be executed, and will receive two parameters:
</p>

<dl>
  <dt><strong><code>req</code> (Object)</strong></dt>
  <dd>
    <p>
    An object that contains information about the request that triggered the route. It contains the following properties:
    </p>

    <dl>
      <dt><strong><code>params</code> (Object or Array)</strong></dt>
      <dd>
        <p>
        Parameters matched by the route path specification.
        </p>

        <p>
        If a string path was used and contained named parameters, then <code>params</code> will be a hash with parameter names as keys and the matched substrings as values. If a regex path was used, <code>params</code> will be an array of matches starting at index <code>0</code> for the full string matched, then <code>1</code> for the first subpattern match, and so on.
        </p>
      </dd>

      <dt><strong><code>path</code> (String)</strong></dt>
      <dd>
        <p>
        The current URL path matched by the route.
        </p>
      </dd>

      <dt><strong><code>query</code> (Object)</strong></dt>
      <dd>
        <p>
        Hash of query string parameters and values specified in the URL, if any.
        </p>
      </dd>
    </dl>
  </dd>

  <dt><strong><code>next</code> (Function)</strong></dt>
  <dd>
    <p>
    A function that will pass control to the next matching route (if any) when called. If not called, no further routes will be executed.
    </p>
  </dd>
</dl>

<p>
Inside a route callback, the <code>this</code> keyword will always refer to the Controller instance that executed that route.
</p>

<h4 id="chaining-routes">Chaining Routes</h4>

<p>
By default, only the first route that matches a URL will be executed, even if there are several routes that match. However, when a route is executed, it will receive a <code>next()</code> function as its second parameter. Calling this function will execute the next matching route if there is one.
</p>

<pre class="code prettyprint">controller.route(&#x27;&#x2F;pie&#x27;, function (req, next) {
  Y.log(&#x27;Callback #1 executed!&#x27;);
  next();
});

controller.route(&#x27;&#x2F;pie&#x27;, function (req) {
  Y.log(&#x27;Callback #2 executed!&#x27;);
});

controller.route(&#x27;&#x2F;pie&#x27;, function (req) {
  Y.log(&#x27;Callback #3 executed!&#x27;);
});

controller.save(&#x27;&#x2F;pie&#x27;);
&#x2F;&#x2F; =&gt; &quot;Callback #1 executed!&quot;
&#x2F;&#x2F; =&gt; &quot;Callback #2 executed!&quot;</pre>


<p>
If you want the first route callback to pass some data along to subsequent callbacks, you can attach that data to the <code>req</code> object, which is shared between all routes that are executed during a single request.
</p>

<pre class="code prettyprint">controller.route(&#x27;&#x2F;ice-cream&#x27;, function (req, next) {
  req.flavor = &#x27;cookie dough&#x27;;
  next();
});

controller.route(&#x27;&#x2F;ice-cream&#x27;, function (req) {
  Y.log(&quot;I sure do like &quot; + req.flavor + &quot; ice cream.&quot;);
});

controller.save(&#x27;&#x2F;ice-cream&#x27;);
&#x2F;&#x2F; =&gt; &quot;I sure do like cookie dough ice cream.&quot;</pre>


<h3 id="updating-the-url">Updating the URL</h3>

<p>
Call the <code>save()</code> or <code>replace()</code> methods to update the URL and store an entry in the browser's history.
</p>

<p>
The only difference between the two is that <code>save()</code> saves a new history entry, while <code>replace()</code> replaces the current history entry.
</p>

<pre class="code prettyprint">&#x2F;&#x2F; Save a new history entry.
controller.save(&#x27;&#x2F;cake&#x27;);

&#x2F;&#x2F; Replace the current history entry with a new one.
controller.replace(&#x27;&#x2F;pie&#x27;);</pre>


<p>
Changing the URL in this way will trigger a dispatch, and will execute the first route that matches the new URL (if any). A dispatch will also be triggered automatically whenever the user uses the browser's back or forward buttons.
</p>

<p>
When you need to provide state information to your route handlers, it's best to provide that information as query parameters in the URL. This way, your application's state is always reflected in the current URL, and can be properly restored when a URL is bookmarked or copied.
</p>

<pre class="code prettyprint">controller.route(&#x27;&#x2F;ice-cream&#x27;, function (req) {
  var flavor = req.query.flavor;

  if (flavor === &#x27;vanilla&#x27;) {
    Y.log(&#x27;Vanilla? How boring.&#x27;);
  } else if (flavor === &#x27;americone dream&#x27;) {
    Y.log(&#x27;Mmmm, Colbert-flavored ice cream.&#x27;);
  } else {
    Y.log(&#x27;Error! Error! Does not compute!&#x27;);
  }
});

controller.save(&#x27;&#x2F;ice-cream?flavor=vanilla&#x27;);
&#x2F;&#x2F; =&gt; &quot;Vanilla? How boring.&quot;

controller.save(&#x27;&#x2F;ice-cream?flavor=americone+dream&#x27;);
&#x2F;&#x2F; =&gt; &quot;Mmm, Colbert-flavored ice cream.&quot;

controller.save(&#x27;&#x2F;ice-cream?flavor=kitten&#x27;);
&#x2F;&#x2F; =&gt; &quot;Error! Error! Does not compute!&quot;</pre>


<h4 id="capturing-link-clicks">Capturing Link Clicks</h4>

<p>
An excellent way to provide progressive enhancement on a page with URLs that can be handled by both the server and the client is to use normal links, and then add a delegated event handler to capture clicks on those links and use client-side routing when JavaScript is available. You can also use this technique to selectively use client-side routing or server-side routing depending on which link is clicked.
</p>

<pre class="code prettyprint">&#x2F;&#x2F; This sample requires the &#x60;node-event-delegate&#x60; module.
YUI().use(&#x27;controller&#x27;, &#x27;node-event-delegate&#x27;, function (Y) {
  &#x2F;&#x2F; ... create a controller instance as described in the sections above ...

  &#x2F;&#x2F; Attach a delegated click handler to listen for clicks on all links on the
  &#x2F;&#x2F; page.
  Y.one(&#x27;body&#x27;).delegate(&#x27;click&#x27;, function (e) {
    &#x2F;&#x2F; Allow the native behavior on middle&#x2F;right-click, or when Ctrl or Command
    &#x2F;&#x2F; are pressed.
    if (e.button !== 1 || e.ctrlKey || e.metaKey) {
      return;
    }

    &#x2F;&#x2F; Remove the non-path portion of the URL, and any portion of the path that
    &#x2F;&#x2F; isn&#x27;t relative to this controller&#x27;s root path.
    var path = controller.removeRoot(e.currentTarget.get(&#x27;href&#x27;));

    &#x2F;&#x2F; If the controller has a route that matches this path, then use the
    &#x2F;&#x2F; controller to update the URL and handle the route. Otherwise, let the
    &#x2F;&#x2F; browser handle the click normally.
    if (controller.hasRoute(path)) {
      e.preventDefault();
      controller.save(path);
    }
  }, &#x27;a&#x27;);
});</pre>


<p>
Now a click on any link, such as <code>&lt;a href=&quot;http:&#x2F;&#x2F;example.com&#x2F;foo&quot;&gt;Click me!&lt;&#x2F;a&gt;</code>, will automatically be handled by the controller if there's a matching route. If there's no matching route, or if the user doesn't have JavaScript enabled, the link click will be handled normally by the browser.
</p>

<h3 id="to-dispatch-or-not-to-dispatch">To Dispatch or Not to Dispatch?</h3>

<p>
Dispatching is what it's called when Controller looks for routes that match the current URL and then executes the callback of the first matching route (if any).
</p>

<p>
A dispatch can be triggered in the following ways:
</p>

<ul>
  <li>Automatically, whenever the URL changes after the initial pageview.</li>
  <li>Manually, by calling the <code>dispatch()</code> method.</li>
  <li>Manually (but only in HTML5 browsers), by calling the <code>upgrade()</code> method when the URL contains a hash-based route that was copied from a legacy browser.</li>
</ul>

<p>
It's important to remember that if a user bookmarks or copies an HTML5 URL generated by Controller and visits that URL later, the full URL will be sent to the server. On the other hand, if a user bookmarks or copies a hash-based URL in a legacy browser and then visits it later, the hash portion of the URL <em>won't</em> be sent to the server.
</p>

<p>
For instance, let's say a user visits your website at <code>http:&#x2F;&#x2F;example.com&#x2F;</code>. On that page, you have the following code:
</p>

<pre class="code prettyprint">&lt;button id=&quot;pie&quot;&gt;Click me if you like pie!&lt;&#x2F;button&gt;

&lt;script&gt;
YUI().use(&#x27;controller&#x27;, &#x27;node&#x27;, function (Y) {
  var controller = new Y.Controller();

  controller.route(&#x27;&#x2F;pie&#x27;, function () {
    &#x2F;&#x2F; Show the user a photo of a delicious pie.
  });

  Y.one(&#x27;#pie&#x27;).on(&#x27;click&#x27;, function () {
    controller.save(&#x27;&#x2F;pie&#x27;);
  });
});
&lt;&#x2F;script&gt;</pre>


<p>
In an HTML5 browser, when the user clicks the button, Controller will change the URL to <code>http:&#x2F;&#x2F;example.com&#x2F;pie</code> and then execute the <code>&#x2F;pie</code> route, but the browser won't contact the server. If the user bookmarks this URL and then loads it again later, the web server will handle the request. If it doesn't recognize the path <code>&#x2F;pie</code>, it may return a 404 error, which would be no good.
</p>

<p>
In a legacy browser, clicking the button will cause the URL to change to <code>http:&#x2F;&#x2F;example.com&#x2F;#&#x2F;pie</code>, and the <code>&#x2F;pie</code> route will be executed, also without contacting the server. The difference is that if the user bookmarks this URL and loads it later, the hash portion won't be sent to the server. The server will only see <code>http:&#x2F;&#x2F;example.com&#x2F;</code>, so it will be necessary to handle the request on the client as well.
</p>

<p>
There are two ways to deal with this. One way would be to implement server-side logic to handle requests for <code>&#x2F;pie</code> and render the appropriate page. To provide fallback support for hash-based URLs, we can modify the client-side code to call the <code>dispatch()</code> method in legacy browsers, by adding the following:
</p>

<pre class="code prettyprint">&#x2F;&#x2F; Always dispatch to an initial route on legacy browsers. Only dispatch to an
&#x2F;&#x2F; initial route on HTML5 browsers if it&#x27;s necessary in order to upgrade a
&#x2F;&#x2F; legacy hash URL to an HTML5 URL.
if (controller.html5) {
  controller.upgrade();
} else {
  controller.dispatch();
}</pre>


<p>
The benefit of this is that HTML5 URLs will be rendered on the server and won't present any difficulties for search crawlers or users with JS disabled. Meanwhile, hash-based URLs will be handled on the client as long as JS is enabled. The drawback with this method is that it may require maintaining duplicate logic on both the server and the client.
</p>

<p>
The other way to handle this would be to configure the server to render the same initial page for all URLs (it would essentially route all paths to the same page), and always dispatch on the client, regardless of the browser's capabilities:
</p>

<pre class="code prettyprint">&#x2F;&#x2F; Dispatch to an initial route on all browsers.
controller.dispatch();</pre>


<p>
On the one hand, this solution avoids most of the server-side complexity and keeps all the controller logic on the client. On the other, it requires the client to support JavaScript, so it won't play well with search crawlers that can't run JavaScript or users who disable JavaScript.
</p>

<h2 id="best-practices">Best Practices</h2>

<h3 id="html5-urls-vs-hash-urls">HTML5 URLs vs. Hash URLs</h3>

<p>
As discussed in <a href="#to-dispatch-or-not-to-dispatch">To Dispatch or Not to Dispatch?</a>, there are benefits and drawbacks to both HTML5 URLs&mdash;that is, URLs generated via the HTML5 history API&mdash;and hash-based URLs. This adds difficulty to any client-side URL-based routing solution, and unfortunately it means you may need to make some tough choices about the architecture of your application.
</p>

<p>
The primary benefit of HTML5 URLs is that they can potentially be handled on the server as well as on the client. This has potential benefits for application architecture (rendering an initial pageview on the server is often faster than rendering it on the client) and for preventing link rot (if you rewrite or replace your application at some point, it's relatively easy to set up server-side redirects to point the old URLs to a new location). That said, HTML5 URLs may require more server-side logic in order to work correctly.
</p>

<p>
Hash-based URLs, on the other hand, can't be handled on the server because browsers don't send the hash portion of a URL to a server. This means they must always be rendered on the client using JavaScript. Even worse, if you eventually rewrite or replace your web app, it's extremely unlikely that you'll be able to keep that old JavaScript around just for the sake of redirecting old URLs, which means any old hash-based URLs in the wild are likely to stop working.
</p>

<p>
In general, the benefits of HTML5 URLs tend to outweigh the drawbacks when compared to hash-based URLs, which is why Controller automatically defaults to using HTML5 URLs in browsers that support it. The hash-based URLs generated by Controller should be used only as a fallback for legacy browsers.
</p>

<h3 id="cross-browser-url-compatibility">Cross-browser URL Compatibility</h3>

<p>
It's very important that any URL generated by Controller be usable in any browser. If a user of a legacy browser copies a URL and shares it with a friend who uses an HTML5 browser, that URL should still work. And if someone copies an HTML5 URL and shares it with a user of a legacy browser, that needs to work too.
</p>

<p>
When a hash-based URL is loaded in an HTML5 browser and <code>dispatch()</code> or <code>upgrade()</code> are called, Controller automatically upgrades the URL to an HTML5 URL. So a URL like <code>http:&#x2F;&#x2F;example.com&#x2F;#&#x2F;pie</code> will become <code>http:&#x2F;&#x2F;example.com&#x2F;pie</code>, and the HTML5 browser will execute the appropriate route handler.
</p>

<p>
The difference between the <code>dispatch()</code> and <code>upgrade()</code> methods is that <code>dispatch()</code> always dispatches to the first route that matches the current URL, whereas <code>upgrade()</code> will only dispatch if the browser is an HTML5 browser and the URL is a legacy hash-based URL that must be handled on the client in order to upgrade it to an HTML5 URL.
</p>

<p>
When an HTML5 URL like <code>http:&#x2F;&#x2F;example.com&#x2F;pie</code> is loaded in a legacy browser, what happens depends on how your server is configured:
</p>

<ul>
  <li><p>If the server is capable of handling the URL, then it should render the page in the appropriate state, and Controller won't need to do anything.</p></li>
  <li><p>If the server is not capable of handling the URL, then it should render the initial page state and you should call Controller's <code>dispatch()</code> method. Controller will parse the HTML5 URL and execute the appropriate route, even in a legacy browser.</p></li>
</ul>

<p>
For more on how dispatching works, see <a href="#to-dispatch-or-not-to-dispatch">To Dispatch or Not to Dispatch?</a>.
</p>

<h3 id="progressive-enhancement-and-seo">Progressive Enhancement and SEO</h3>

<p>
In general, HTML5 URLs that can be rendered by the server when necessary provide the best support for both progressive enhancement (by rendering initial pageviews more quickly, even in browsers with JavaScript disabled) and for search engine optimization (by allowing you to use real, non hash-based URLs that can be crawled by search bots, which may not support JavaScript).
</p>

<p>
Being able to render the same application states both on the server and the client may require you to write duplicate code. However, if you use JavaScript on the server, and in particular if you use <a href="http://nodejs.org/">Node.js</a>, you may be able to share code.
</p>

<p>
Controller's routing style and route specification format are intentionally very similar to those of the <a href="http://expressjs.com/">Express.js</a> server-side framework. With a little care, you may be able to use the same route handler code on both the server and the client.
</p>

<h4 id="supporting-googles-ajax-crawling-scheme">Supporting Google's Ajax Crawling Scheme</h4>

<p>
One of the problems with the hash-based URLs Controller uses to support legacy browsers is that most search engines don't distinguish between a URL with a hash fragment and one without. This means that, to a search bot, the URLs <code>http:&#x2F;&#x2F;example.com&#x2F;</code> and <code>http:&#x2F;&#x2F;example.com&#x2F;#&#x2F;pie</code> might look the same, even though they might represent completely different content in your application.
</p>

<p>
Google's <a href="http://code.google.com/web/ajaxcrawling/">Ajax Crawling Scheme</a> specifies a way to make hash-based URLs crawlable by the GoogleBot if you're willing to implement some extra server-side logic.
</p>

<p>
To indicate to the GoogleBot that your hash URLs are crawlable, the hash must be prefixed by <code>#!</code> instead of the default <code>#</code>. You can make Controller do this automatically by setting the value of the static <code>Y.HistoryHash.hashPrefix</code> property before initializing any Controller instances:
</p>

<pre class="code prettyprint">Y.HistoryHash.hashPrefix = &#x27;!&#x27;;</pre>


<p>
Next, read Google's <a href="http://code.google.com/web/ajaxcrawling/docs/getting-started.html">getting started guide</a> for a description of how the Ajax crawling scheme works and the additional changes you'll need to make to your application. Most of the changes you'll need to make will have to happen in your server-side logic.
</p>

<p>
Don't skip the server-side changes! Without them, using the <code>#!</code> prefix won't do you any good, and may even hurt the search ranking of your pages.
</p>

<h2 id="known-limitations">Known Limitations</h2>

<ul>
  <li><p><strong>HTML5 history is not currently supported by any version of Internet Explorer.</strong> This includes Internet Explorer 9 and developer preview releases of IE10 as of the time these docs were written. Please feel free to let Microsoft know how you feel about this.</p></li>

  <li><p><strong>Android 2.x is forced to use hash-based history due to <a href="http://code.google.com/p/android/issues/detail?id=17471">a bug</a> in Android's HTML5 history implementation.</strong> This bug does not affect Android 3.0 and higher.</p></li>

  <li><p><strong>Hash-based URLs are case-insensitive in Internet Explorer 8 and 9</strong>. Most browsers follow the HTML5 spec and treat URLs&mdash;including hash-based URLs&mdash;as case-sensitive. IE8 and IE9 ignore case in hash-based URLs, so changing a hash-based URL from <code>&#x2F;foo</code> to <code>&#x2F;Foo</code> won't trigger a dispatch.</p></li>

  <li><p><strong>Internet Explorer 6 and 7 only retain the most recent hash-based URL from a previous pageview after navigating to another page and returning.</strong> However, history entries created within a single pageview will persist for the duration of that pageview, and bookmarked URLs will still work in all cases.</p></li>

  <li><p><strong>In Internet Explorer 6 and 7, the page titles displayed for history entries in the browser's history dropdown menu are not correct.</strong> Instead of showing the title of each page, it shows part of the URL of each page.</p></li>
</ul>
</div>
        </div>

        <div id="sidebar" class="yui3-u">
            
                <div id="toc" class="sidebox">
                    <div class="hd">
                        <h2 class="no-toc">Table of Contents</h2>
                    </div>

                    <div class="bd">
                        <ul class="toc">
<li>
<a href="#getting-started">Getting Started</a>
</li>
<li>
<a href="#url-based-routing-on-the-client">URL-based Routing on the Client?</a>
</li>
<li>
<a href="#sample-urls">Sample URLs</a>
</li>
<li>
<a href="#using-controller">Using Controller</a>
<ul class="toc">
<li>
<a href="#instantiating-controller">Instantiating Controller</a>
<ul class="toc">
<li>
<a href="#config-properties">Config Properties</a>
</li>
<li>
<a href="#read-only-properties">Read-Only Properties</a>
</li>
<li>
<a href="#setting-the-root-path">Setting the Root Path</a>
</li>
</ul>
</li>
<li>
<a href="#extending-ycontroller">Extending <code>Y.Controller</code></a>
</li>
<li>
<a href="#routing">Routing</a>
<ul class="toc">
<li>
<a href="#paths-placeholders-and-regexps">Paths, Placeholders, and RegExps</a>
</li>
<li>
<a href="#route-callbacks">Route Callbacks</a>
</li>
<li>
<a href="#chaining-routes">Chaining Routes</a>
</li>
</ul>
</li>
<li>
<a href="#updating-the-url">Updating the URL</a>
<ul class="toc">
<li>
<a href="#capturing-link-clicks">Capturing Link Clicks</a>
</li>
</ul>
</li>
<li>
<a href="#to-dispatch-or-not-to-dispatch">To Dispatch or Not to Dispatch?</a>
</li>
</ul>
</li>
<li>
<a href="#best-practices">Best Practices</a>
<ul class="toc">
<li>
<a href="#html5-urls-vs-hash-urls">HTML5 URLs vs. Hash URLs</a>
</li>
<li>
<a href="#cross-browser-url-compatibility">Cross-browser URL Compatibility</a>
</li>
<li>
<a href="#progressive-enhancement-and-seo">Progressive Enhancement and SEO</a>
<ul class="toc">
<li>
<a href="#supporting-googles-ajax-crawling-scheme">Supporting Google's Ajax Crawling Scheme</a>
</li>
</ul>
</li>
</ul>
</li>
<li>
<a href="#known-limitations">Known Limitations</a>
</li>
</ul>
                    </div>
                </div>
            

            

            
        </div>
    </div>
</div>

<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>

</body>
</html>
